package com.tbit.uqbike.client.aop.charge;

import com.tbit.uqbike.client.constant.RechargeConstant;
import com.tbit.uqbike.client.constant.RedisConstant;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.service.RedisService;
import com.tbit.uqbike.client.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Optional;

/**
 * 充值结束订单限制
 *
 *
 * @author <a href="mailto:chen.chaoxiong@tbit.com.cn">ChenChaoXiong</a>
 * @since 2024/5/31
 */
@Component
@Aspect
public class ChargeReturnBikeLimitAspect {

    @Autowired
    private RedisService redisService;

    @Autowired
    private TokenService tokenService;

    @Value("${charge.returnBike.limit.switch:false}")
    private boolean checkSwitch = false;



    @Around("@annotation(ChargeReturnBikeLimit)")
    public void chargeReturnBikeLimit(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Object[] args = joinPoint.getArgs();
        Parameter[] parameters = method.getParameters();

        Integer rechargeType = null;
        String token = null;

        for (int i = 0; i < parameters.length; i++) {
            if (parameters[i].isAnnotationPresent(RechargeTypeParam.class) && args[i] instanceof Integer) {
                rechargeType = (Integer) args[i];
            }
            if (parameters[i].isAnnotationPresent(TokenParam.class) && args[i] instanceof String) {
                token = (String) args[i];
            }
        }

        if (rechargeType != null && rechargeType.equals(RechargeConstant.recharge_returnBike) && StringUtils.isNotBlank(token)) {
            Integer userId = Optional.ofNullable(tokenService.getUser(token)).map(User::getUserId).orElseThrow(() -> new BaseException("用户不存在"));
            String orderNo = redisService.get(RedisConstant.RECHARGE_RETURNBIKE_PAYMENT_FINISH + userId);
            if (StringUtils.isNotBlank(orderNo)){
                throw new BaseException("请勿重复支付，您上一笔支付已成功，请联系客服关单");
            }
        }

        joinPoint.proceed();
    }

}
